package servlet.user.test;

import DBCP.MyDBCP;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/signup")
public class SignUpServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        System.out.println(username+" : "+password);

        Connection con = MyDBCP.getConnenction();
        String selectSql = "select  * from db_user.user where username = ?";
        String insertSql = "insert into db_user.user values (null,?,md5(?),null,null)";
        try {
            PreparedStatement ps_select= con.prepareStatement(selectSql);
            ps_select.setString(1,username);
            ResultSet resultSet = ps_select.executeQuery();
            if (resultSet.next()){
                req.getSession().setAttribute("message","username is alreadly!!");
                req.getRequestDispatcher("Day02/user/index.jsp").forward(req,resp);
            }else {
                PreparedStatement ps_insert = con.prepareStatement(insertSql);
                ps_insert.setString(1,username);
                ps_insert.setString(2,password);
                ps_insert.executeUpdate();
                resp.sendRedirect("Day02/user/index.jsp");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
